// 全局变量
let currentVideo = null;
let videoDuration = 0;
let currentFilename = '';

// DOM 元素
const uploadArea = document.getElementById('uploadArea');
const videoFile = document.getElementById('videoFile');
const uploadProgress = document.getElementById('uploadProgress');
const videoInfoSection = document.getElementById('videoInfoSection');
const timeSelectionSection = document.getElementById('timeSelectionSection');
const splitSection = document.getElementById('splitSection');
const resultSection = document.getElementById('resultSection');

const startTimeSlider = document.getElementById('startTimeSlider');
const endTimeSlider = document.getElementById('endTimeSlider');
const startTimeInput = document.getElementById('startTimeInput');
const endTimeInput = document.getElementById('endTimeInput');
const segmentDuration = document.getElementById('segmentDuration');

const splitBtn = document.getElementById('splitBtn');
const splitProgress = document.getElementById('splitProgress');
const downloadBtn = document.getElementById('downloadBtn');

// 工具函数
function formatTime(seconds) {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = Math.floor(seconds % 60);
    return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
}

function showToast(message, type = 'info') {
    const toast = document.getElementById('toast');
    const toastBody = document.getElementById('toastBody');
    
    toastBody.textContent = message;
    
    // 设置toast样式
    toast.className = `toast ${type === 'error' ? 'bg-danger text-white' : 'bg-success text-white'}`;
    
    const bsToast = new bootstrap.Toast(toast);
    bsToast.show();
}

function updateTimeDisplay() {
    const startPercent = parseFloat(startTimeSlider.value);
    const endPercent = parseFloat(endTimeSlider.value);
    
    // 确保开始时间小于结束时间
    if (startPercent >= endPercent) {
        if (startTimeSlider === document.activeElement) {
            endTimeSlider.value = Math.min(100, startPercent + 1);
        } else {
            startTimeSlider.value = Math.max(0, endPercent - 1);
        }
    }
    
    const startTime = (videoDuration * parseFloat(startTimeSlider.value)) / 100;
    const endTime = (videoDuration * parseFloat(endTimeSlider.value)) / 100;
    const duration = endTime - startTime;
    
    startTimeInput.value = formatTime(startTime);
    endTimeInput.value = formatTime(endTime);
    segmentDuration.textContent = formatTime(duration);
}

// 文件上传处理
uploadArea.addEventListener('click', () => {
    videoFile.click();
});

uploadArea.addEventListener('dragover', (e) => {
    e.preventDefault();
    uploadArea.classList.add('dragover');
});

uploadArea.addEventListener('dragleave', () => {
    uploadArea.classList.remove('dragover');
});

uploadArea.addEventListener('drop', (e) => {
    e.preventDefault();
    uploadArea.classList.remove('dragover');
    
    const files = e.dataTransfer.files;
    if (files.length > 0) {
        handleFileUpload(files[0]);
    }
});

videoFile.addEventListener('change', (e) => {
    if (e.target.files.length > 0) {
        handleFileUpload(e.target.files[0]);
    }
});

async function handleFileUpload(file) {
    // 检查文件类型
    if (!file.type.startsWith('video/')) {
        showToast('请选择视频文件！', 'error');
        return;
    }
    
    // 显示上传进度
    uploadProgress.classList.remove('d-none');
    const progressBar = uploadProgress.querySelector('.progress-bar');
    
    const formData = new FormData();
    formData.append('video', file);
    
    try {
        // 模拟上传进度
        let progress = 0;
        const progressInterval = setInterval(() => {
            progress += Math.random() * 30;
            if (progress > 90) progress = 90;
            progressBar.style.width = progress + '%';
        }, 200);
        
        const response = await fetch('/upload', {
            method: 'POST',
            body: formData
        });
        
        clearInterval(progressInterval);
        progressBar.style.width = '100%';
        
        const result = await response.json();
        
        if (result.success) {
            currentFilename = result.filename;
            showToast('文件上传成功！');
            await getVideoInfo(result.filename);
        } else {
            showToast(result.error || '上传失败', 'error');
        }
    } catch (error) {
        showToast('上传失败: ' + error.message, 'error');
    } finally {
        setTimeout(() => {
            uploadProgress.classList.add('d-none');
            progressBar.style.width = '0%';
        }, 1000);
    }
}

async function getVideoInfo(filename) {
    try {
        const response = await fetch('/video-info', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({ filename: filename })
        });
        
        const result = await response.json();
        
        if (result.success) {
            videoDuration = result.duration;
            
            // 更新视频信息显示
            document.getElementById('videoFileName').textContent = filename;
            document.getElementById('videoDuration').textContent = result.duration_formatted;
            document.getElementById('videoResolution').textContent = result.size;
            document.getElementById('videoFps').textContent = result.fps.toFixed(1);
            
            // 显示相关区域
            videoInfoSection.classList.remove('d-none');
            videoInfoSection.classList.add('fade-in');
            
            timeSelectionSection.classList.remove('d-none');
            timeSelectionSection.classList.add('fade-in');
            
            splitSection.classList.remove('d-none');
            splitSection.classList.add('fade-in');
            
            // 初始化时间选择器
            updateTimeDisplay();
            
            showToast('视频信息获取成功！');
        } else {
            showToast(result.error || '获取视频信息失败', 'error');
        }
    } catch (error) {
        showToast('获取视频信息失败: ' + error.message, 'error');
    }
}

// 时间滑块事件监听
startTimeSlider.addEventListener('input', updateTimeDisplay);
endTimeSlider.addEventListener('input', updateTimeDisplay);

// 切分按钮事件
splitBtn.addEventListener('click', async () => {
    if (!currentFilename) {
        showToast('请先上传视频文件！', 'error');
        return;
    }
    
    const startTime = (videoDuration * parseFloat(startTimeSlider.value)) / 100;
    const endTime = (videoDuration * parseFloat(endTimeSlider.value)) / 100;
    
    if (startTime >= endTime) {
        showToast('开始时间必须小于结束时间！', 'error');
        return;
    }
    
    // 显示处理进度
    splitBtn.disabled = true;
    splitProgress.classList.remove('d-none');
    resultSection.classList.add('d-none');
    
    try {
        const response = await fetch('/split', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                filename: currentFilename,
                start_time: startTime,
                end_time: endTime
            })
        });
        
        const result = await response.json();
        
        if (result.success) {
            // 显示成功结果
            document.getElementById('resultMessage').textContent = result.message;
            resultSection.classList.remove('d-none');
            resultSection.classList.add('fade-in');
            
            // 设置下载按钮
            downloadBtn.onclick = () => {
                window.open(`/download/${result.output_filename}`, '_blank');
            };
            
            showToast('视频切分成功！');
        } else {
            showToast(result.error || '视频切分失败', 'error');
        }
    } catch (error) {
        showToast('视频切分失败: ' + error.message, 'error');
    } finally {
        splitBtn.disabled = false;
        splitProgress.classList.add('d-none');
    }
});

// 页面加载完成后的初始化
document.addEventListener('DOMContentLoaded', () => {
    console.log('视频切分工具已加载');
});